<!--文档详细表管理-->
<template>
  <div id="contentArticle" class="app-container flex-row">
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:300px">
      <category-tree v-model="listQuery.categoryId" mode="news" @change="handleCategoryChange" />
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item label="标题：">
            <el-input v-model="listQuery.title" clearable placeholder="请输入文章标题" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="关键字：">
            <el-input v-model="listQuery.keywords" clearable placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="作者：">
            <el-input v-model="listQuery.author" clearable placeholder="请输入作者" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="发布时间：">
            <div class="flex-row">
              <el-date-picker v-model="listQuery.startDate" style="flex: 1;" type="datetime" value-format="timestamp" placeholder="请选择" clearable />
              <span style="padding: 0 10px;">至</span>
              <el-date-picker v-model="listQuery.endDate" style="flex: 1;" type="datetime" value-format="timestamp" placeholder="请选择" clearable />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>

          </el-form-item>
        </el-form>
      </div>

      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar create-text="发布新闻" :remove="status==='3'" remove-text="彻底删除" @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
        </div>
        <el-tabs v-model="status" class="common-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="所有" name="-1" />
          <el-tab-pane label="待发布" name="1" />
          <el-tab-pane label="已发布" name="2" />
          <el-tab-pane label="草稿" name="0" />
          <el-tab-pane label="回收站" name="3" />
        </el-tabs>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="60" />
          <el-table-column align="center" prop="id" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="封面" prop="image1" width="130" align="center">
            <template slot-scope="scope">
              <img :src="common.getFileView(scope.row.image1)" style="width: 92px;height: 46px;" data-default="no_news" @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" min-width="500" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>
                <el-tag v-if="scope.row.isOriginal===1" style="margin-right: 5px;" size="mini" type="danger" effect="plain"> 原创</el-tag>
                <el-tag v-if="scope.row.isTop===1" style="margin-right: 5px;" size="mini" type="danger" effect="plain"> 置顶</el-tag>
                <span style="font-size: 14px;font-weight:bold;" class="title-hover" @click="showDetail(scope.row)">{{ scope.row.title }}</span>
              </div>
              <div>
                <el-tag v-if="scope.row.isDeleted===1" style="margin-right: 5px;" size="mini" type="danger"> 回收站</el-tag>
                <el-tag v-if="scope.row.status===1" style="margin-right: 5px;" size="mini" type="info"> 待发布</el-tag>
                <el-tag v-if="scope.row.status===2" style="margin-right: 5px;" size="mini" type="primary"> 已发布</el-tag>
                <el-tag v-if="scope.row.status===0" style="margin-right: 5px;" size="mini" type="warning"> 草稿</el-tag>
                <span class="color-primary" style="margin-right: 5px;">[{{ scope.row._fullCategoryName }}]</span>
                <span v-if="scope.row.createdBy" style="margin-right: 5px;">{{ scope.row.createdBy | optionUserFormat }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="浏览" width="70" prop="views" sortable />
          <el-table-column label="评论" width="70" prop="comments" sortable />
          <el-table-column label="收藏" width="70" prop="collections" sortable />
          <el-table-column label="点赞" width="70" prop="thumbUpNum" sortable />
          <el-table-column prop="gmtCreated" sortable label="添加日期" width="160">
            <template slot-scope="scope">
              {{ scope.row.gmtCreated | formatDate('yyyy-MM-dd hh:mm') }}
            </template>
          </el-table-column>
          <el-table-column prop="publishDate" sortable label="发布日期" width="160">
            <template slot-scope="scope">
              {{ scope.row.publishDate | formatDate('yyyy-MM-dd hh:mm') }}<br>
            </template>
          </el-table-column>
          <el-table-column prop="publishDate" label="作者信息" width="160">
            <template slot-scope="scope">
              <div v-if="scope.row.source" class="color-primary" style="margin-right: 5px;"><label class="color-default">来源：</label>{{ scope.row.source }}</div>
              <div class="color-primary"><label v-if="scope.row.author" class="color-default">作者：</label>{{ scope.row.author }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" fixed="right" width="110">
            <template slot-scope="scope">
              <template v-if="scope.row.isDeleted===1">
                <button-option icon="el-icon-refresh-right" skin="default" title="从回收站恢复" @click="handleRecovery(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="彻底删除" @click="handleRemoveSingle(scope.row)" />
              </template>
              <template v-else>
                <button-option v-if="scope.row.status!==2" icon="el-icon-edit" skin="primary" title="文章编辑" @click="handleUpdate(scope.row)" />
                <button-option v-if="[2].includes(scope.row.status)" icon="iconQrcode" icon-type="svg" skin="primary" title="二维码" @click="handleQrcode(scope.row)" />
                <button-option v-if="[1].includes(scope.row.status)" icon="el-icon-s-promotion" skin="primary" title="发布上线" @click="handleRelease(scope.row)" />
                <button-option v-if="[2].includes(scope.row.status)" icon="el-icon-refresh-left" skin="danger" title="撤销发布" @click="handleRevokePublication(scope.row)" />
                <button-option v-if="scope.row.status===2 && scope.row.syncMaterialLibrary===1" icon-type="svg" icon="iconSyncCancel" skin="danger" title="从微信素材库撤销同步" @click="handleCancelSyncMaterialLibrary(scope.row)" />
                <button-option v-if="scope.row.status===2 && scope.row.syncMaterialLibrary===0" icon-type="svg" icon="iconSynchronization" skin="primary" title="同步至微信素材库" @click="handleSyncMaterialLibrary(scope.row)" />
                <button-option icon="el-icon-brush" skin="warning" title="移入回收站" @click="handleMoveRecycleBin(scope.row)" />
              </template>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>
    <model-dialog
      title="H5二维码"
      :visible.sync="dialogVisible"
      width="220px"
      :show-close="false"
      @close="dialogVisible=!dialogVisible">
      <div class="preview-qrcode-container">
        <div id="qrCode" ref="qrCodeDiv" class="qrcode" />
        <div class="scan-tip">手机扫码预览</div>
      </div>
    </model-dialog>
    <syncWxPub ref="syncWxPub" @success="fetchData" />
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import categoryTree from './categoryTree.vue'
import syncWxPub from './syncWxPub.vue'
export default {
  components: { categoryTree, syncWxPub },

  data() {
    return {
      status: '-1',
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: '-gmtCreated',
        isDeleted: 0,
        title: null,
        keywords: null,
        author: null,
        startDate: '',
        endDate: ''
      },

      multipleSelectionRecords: [],
      dialogVisible: false
    }
  },
  watch: {
    'listQuery.categoryId': function(val) {
    }
  },
  created() {
  },
  methods: {
    handleTabClick() {
      if (this.status === '3') {
        this.listQuery = {
          ...this.listQuery,
          isDeleted: 1,
          status: null
        }
      } else {
        this.listQuery = {
          ...this.listQuery,
          status: this.status,
          isDeleted: 0
        }
      }
      this.fetchData()
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '-gmtCreated'
      }
      this.handleFilter()
    },
    // 表格自带方法结束
    handleCategoryChange(val) {
      this.listQuery = {
        ...this.listQuery,
        treeNumber: val.treeNumber
      }
      this.handleReset()
    },
    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        title: null,
        keywords: null,
        author: null,
        startDate: '',
        endDate: '',
        sort: '-gmtCreated'
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('contentArticlePageV2', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    showDetail(row) {
      // details/:category/:id
      this.$router.push({ name: 'contentDetails', params: { id: row.id }})
    },
    /* 新增*/
    handleCreate() {
      this.$router.push({ name: 'contentCreate', query: { }})
    },
    /* 编辑*/
    handleUpdate(row) {
      this.$router.push({ name: 'contentCreate', query: { id: row.id }})
    },
    // 发布
    handleRelease(row) {
      this.$confirm(`您确定要发布【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('contentArticleRelease', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('发布成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 撤销发布
    handleRevokePublication(row) {
      this.$confirm(`您确定要撤销发布的【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('contentArticleRevokePublication', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('撤销成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 恢复
    handleRecovery(row) {
      this.$confirm(`您确定要从回收站中恢复【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('contentArticleRecovery', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('恢复成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 移入回收站
    handleMoveRecycleBin(row) {
      this.$confirm(`您确定要将【${row.title}】移入回收站, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('contentArticleMoveRecycleBin', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('移入回收站成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    handleSyncMaterialLibrary(row) {
      this.$confirm(`您确定要将【${row.title}】同步至微信素材库, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.syncWxPub.init({ id: row.id, title: row.title })
      }).catch(() => { })
    },
    handleCancelSyncMaterialLibrary(row) {
      this.$confirm(`您确定要将【${row.title}】从微信素材库取消同步, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('contentArticleRevokeWxPub', row.id).then(response => {
          this.$modal.msgSuccess('撤销成功!')
          this.fetchData()
        }).catch(() => {
        })
      }).catch(() => { })
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('contentArticleRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleQrcode(row) {
      this.dialogVisible = true
      this.$nextTick(() => {
        document.getElementById('qrCode').innerHTML = ''
        new QRCode(this.$refs.qrCodeDiv, { //
          text: this.T.getUrl() + '#/article/h5/preview/' + row.id,
          width: 120,
          height: 120,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
      })
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
